using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Xivo.Shared;

namespace Xivo {
  public partial class MainForm : Form, Shared.IXivoPlugin {
    List<IXivoPlugin> Plugins = new List<IXivoPlugin>();
    Shared.RadioBase Radio;
    bool DesiredPowerState = true;

    private void MainForm_Load(object sender, EventArgs e) {

      hotkey1.RegisterKey(TvShow.Hotkey.ModiferKey.MOD_WIN, Keys.X);
      //hotkey1.RegisterKey(TvShow.Hotkey.ModiferKey.MOD_WIN, Keys.M);
      Plugins.Add(this);
      Plugins.Add(Radio);
      Plugins.Add(channelListControl1);

      // get configration
      foreach (IXivoPlugin i in Plugins) {
        i.Init();
      }

      statusRadioType.Text = Radio.RadioType;
      Radio.CurrentChannel = Properties.Settings.Default.DefaultChannel;
      Radio.PortName = Properties.Settings.Default.Port;
      Radio.onRadioIDReceived += new Delegates.StringEvent(Radio_onRadioIDReceived);
      Radio.onPowerChange += new Delegates.IntEvent(Radio_onPowerChange);
      Radio.onSignalDataReceived += new Delegates.SignalEvent(Radio_onSignalDataReceived);
      Radio.onMuteChange += new Delegates.IntEvent(Radio_onMuteChange);
      Radio.onChannelInfoChange += new Delegates.InfoEvent(Radio_onChannelInfoChange);
      scheduleControl1.RecordPath = Properties.Settings.Default.RecordPath;
      options.OkClicked += new EventHandler(options_OkClicked);

      foreach (IXivoPlugin i in Plugins) {
        i.Start();
      }

      // read channel list and favorites
      hotList.LoadList("hotlist.txt");
      scheduleControl1.LoadSchedule("schedule.txt");

      // get config info
      //mixerControl1.LineIndex = Properties.Settings.Default.MixerLine;
      //scheduleControl1.timer_Tick();
      scheduleControl1.StartTimer();
    }

    void Radio_onMuteChange(int value) {
      if (InvokeRequired)
        Invoke(new Xivo.Shared.Delegates.IntEvent(Radio_onMuteChange), new object[] { value });
      else {
        if (value == 0)
          statusMuted.Text = " Mute ";
        else
          statusMuted.Text = "[Muted]";
      }
    }

    void Radio_onSignalDataReceived(int[] data) {
      if (InvokeRequired)
        Invoke(new Xivo.Shared.Delegates.SignalEvent(Radio_onSignalDataReceived), new object[] { data });
      else {
        if (data[0] != 0) {
          progSat.Value = data[1];
          progTer.Value = data[2];
        }
        else {
          progSat.Value = 0;
          progTer.Value = 0;
        }
      }
    }

    void Radio_onPowerChange(int value) {
      if (InvokeRequired)
        Invoke(new Xivo.Shared.Delegates.IntEvent(Radio_onPowerChange), new object[] { value });
      else {
        if (value == 1) {
          statusOn.Text = "[On]";
          statusOff.Text = "Off";
        }
        else {
          statusOn.Text = "On";
          statusOff.Text = "[Off]";
          lChannelName.Text = "";
          lChannelNumber.Text = "";
          lArtist.Text = "";
          lTitle.Text = "";
        }
      }
    }

    void Radio_onRadioIDReceived(string value) {
      if (InvokeRequired)
        Invoke(new Xivo.Shared.Delegates.StringEvent(Radio_onRadioIDReceived), new object[] { value });
      else {
        sRadioID.Text = "ID:" + Radio.RadioID;
      }
    }

    void Radio_onChannelInfoChange(ChannelInfo info) {
      if (InvokeRequired)
        Invoke(new Xivo.Shared.Delegates.InfoEvent(Radio_onChannelInfoChange), new object[] { info });
      else {
        updateChannelInfo(info);
      }
    }

    void Shared.IXivoPlugin.Init() {
      Left = Properties.Settings.Default.left;
      Top = Properties.Settings.Default.top;
      Width = Properties.Settings.Default.width;
      Height = Properties.Settings.Default.height;
    }

    void IXivoPlugin.Start() {
    }

    void IXivoPlugin.ShutDown() {
    }


    //
    // un-refactored code
    //

    OptionsDialog options = new OptionsDialog();
    HotList hotList = new HotList();
    //MixerTest.MixerForm mixer;

    public MainForm() {
      Radio = Xivo.Shared.Common.Radio;
      InitializeComponent();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
      this.Close();
    }

    private void bPowerOn_Click(object sender, EventArgs e) {
      Radio.PowerState = 1;
    }

    void options_OkClicked(object sender, EventArgs e) {
      Properties.Settings.Default.RecordPath = options.RecordPath;
      Properties.Settings.Default.Port = options.ComPort;
      Properties.Settings.Default.DefaultChannel = Radio.CurrentChannel;
      Properties.Settings.Default.XMDirect = options.XMDirect;
      Properties.Settings.Default.RecordSource = options.RecordSource;
      Properties.Settings.Default.Save();
      Application.Restart();
    }

    private void bPowerOff_Click(object sender, EventArgs e) {
      Radio.PowerState = 0;
    }

    void updateChannelInfo(ChannelInfo info) {
      if (info != null && info.channel == Radio.CurrentChannel) {
        Text = "XiVo - " + info.longTitle;
        if (info.station != null) lChannelName.Text = info.station.Trim().Replace("&", "&&");
        if (info.genre != null) lChannelName.Text += ": " + info.genre.Trim().Replace("&", "&&");
        if (info.channel != 0) lChannelNumber.Text = info.channelStr;
        if (info.longArtist != null)
          lArtist.Text = info.longArtist.Replace("&", "&&");
        else
          lArtist.Text = "";
        if (info.longTitle != null)
          lTitle.Text = info.longTitle.Replace("&", "&&");
        else
          lTitle.Text = "";
      }
    }

    private void viewHotlistToolStripMenuItem_Click(object sender, EventArgs e) {
      hotList.Visible = true;
    }

    private void lvChannels_Click(object sender, EventArgs e) {
      ListView s = (ListView)sender;
      byte toCh = Byte.Parse(s.SelectedItems[0].Text);
      Radio.CurrentChannel = toCh;
    }

    private void bChannelUp_Click(object sender, EventArgs e) {
      channelListControl1.ChannelUp();
    }

    private void bChannelDown_Click(object sender, EventArgs e) {
      channelListControl1.ChannelDown();
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
      foreach (IXivoPlugin i in Plugins)
        i.ShutDown();

      channelListControl1.Cleanup();

      // save configuration items 
      hotList.Save("hotlist.txt");
      scheduleControl1.SaveSchedule("schedule.txt");

      if (WindowState == FormWindowState.Normal) {
        Properties.Settings.Default.left = Left;
        Properties.Settings.Default.top = Top;
        Properties.Settings.Default.width = Width;
        Properties.Settings.Default.height = Height;
      }
      Properties.Settings.Default.DefaultChannel = Radio.CurrentChannel;
      Properties.Settings.Default.RecordPath = scheduleControl1.RecordPath;
      //Properties.Settings.Default.MixerLine = mixerControl1.LineIndex;
      Properties.Settings.Default.Save();

      System.Windows.Forms.Application.DoEvents();
    }

    //private void showMixerToolStripMenuItem_Click(object sender, EventArgs e)
    //{
    //  mixer = new MixerTest.MixerForm();
    //  mixer.Show();
    //}

    private void playThroughToolStripMenuItem_Click(object sender, EventArgs e) {
      ToolStripMenuItem s = (ToolStripMenuItem)sender;
      s.Checked = !s.Checked;
    }

    private void tbEnterChannel_Enter(object sender, EventArgs e) {
      lChannelEntry.Text = "";
    }

    private void tbEnterChannel_KeyDown(object sender, KeyEventArgs e) {
      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return) {
      }
    }

    private void MainForm_MouseWheel(object sender, MouseEventArgs e) {
      channelListControl1.ChannelListControl_MouseWheel(sender, e);
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
      System.Windows.Forms.Application.Exit();
    }

    private void MainForm_KeyDown(object sender, KeyEventArgs e) {
      switch (e.KeyCode) {
        //case Keys.Up:
        //  mixerControl1.VolumeInc();
        //  break;
        //case Keys.Down:
        //  mixerControl1.VolumeDec();
        //  break;
        case Keys.Add:
          bChannelDown_Click(null, null);
          break;
        case Keys.Subtract:
          bChannelUp_Click(null, null);
          break;
        case Keys.Back:
          if (lChannelEntry.Text.Length > 0)
            lChannelEntry.Text = lChannelEntry.Text.Substring(
              0, lChannelEntry.Text.Length - 1);
          break;
        case Keys.M:
          Radio.MuteState = (Radio.MuteState + 1) % 2;
          break;
        default:
          //System.Diagnostics.Debug.WriteLine("Key: " + e.KeyCode.ToString());
          break;
      }
    }

    private void channelListControl1_onHotListAdd(ChannelListControl sender, string e) {
      hotList.Add(e);
    }

    private void notifyIcon1_Click(object sender, EventArgs e) {
      Show();
      if (WindowState == FormWindowState.Minimized)
        WindowState = FormWindowState.Normal;
      notifyIcon1.Visible = false;
    }

    private void hideToolStripMenuItem_Click(object sender, EventArgs e) {
      notifyIcon1.Visible = true;
      Hide();
    }

    private void MainForm_KeyPress(object sender, KeyPressEventArgs e) {
      if (e.KeyChar >= '0' && e.KeyChar <= '9') {
        lChannelEntry.Text += e.KeyChar;
        int newChannel;
        if (int.TryParse(lChannelEntry.Text, out newChannel)) {
          if (lChannelEntry.Text.Length == 3 || newChannel >= 26) {
            Radio.CurrentChannel = newChannel;
            lChannelEntry.Text = "";
          }
        }
      }
    }

    private void optionsToolStripMenuItem_Click(object sender, EventArgs e) {

      options.RecordPath = scheduleControl1.RecordPath;
      options.ComPort = Radio.PortName;
      options.Show();
    }

    private void MainForm_VisibleChanged(object sender, EventArgs e) {
      if (options.Visible)
        options.Activate();
    }

    private void hotkey1_HotKeyPressed(Keys Key) {
      switch (Key) {
        case Keys.X:
          Show();
          this.WindowState = FormWindowState.Normal;
          notifyIcon1.Visible = false;
          this.Activate();
          break;
        case Keys.M:
          Radio.MuteState = (Radio.MuteState + 1) % 2;
          break;
      }
    }

    private void channelListControl1_Load(object sender, EventArgs e) {

    }

    private void sPower_Click(object sender, EventArgs e) {
      DesiredPowerState = true;
      Radio.PowerState = 1;
    }

    private void toolStripStatusLabel3_Click(object sender, EventArgs e) {
      DesiredPowerState = false;
      Radio.PowerState = 0;
    }

    private void toolStripStatusLabel3_Click_1(object sender, EventArgs e) {
      Radio.MuteState = (Radio.MuteState + 1) % 2;
    }

  }
}
